package com.ztz.mynewdemo.activity;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.bumptech.glide.Glide;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.ztz.mynewdemo.R;
import com.ztz.mynewdemo.Service.UpdateService;
import com.ztz.mynewdemo.fragment.UseInfoFragment;
import com.ztz.mynewdemo.utils.BaiDuLocationUtils;
import com.ztz.mynewdemo.utils.HttpUtil;
import com.ztz.mynewdemo.utils.NewsApi;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;


public class LocateActivity extends AppCompatActivity {
    private static final String TAG = "LocateActivity";
    public static final String LONGITUDE = "longitude";
    public static final String LATITUDE = "latitude";
    public LocationClient mLocationClient;
    private TextView tv_position;
    private MapView mapView;
    private BaiduMap baiduMap;
    private ImageView iv_Bing;
    private boolean isFirstLocate = true;
    double mLatitude;
    double mLongitude;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(new MyLocationListener());
        setContentView(R.layout.activity_locate);
//        tv_position=(TextView)findViewById(R.id.tv_position);
        mapView = (MapView) findViewById(R.id.bMapView);
        baiduMap = mapView.getMap();
        iv_Bing = (ImageView) findViewById(R.id.iv_bing);
        //显示正常地图
        baiduMap.setMapType(BaiduMap.MAP_TYPE_NORMAL);
        baiduMap.setMyLocationEnabled(true);
        List<String> permissionList = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(LocateActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (!permissionList.isEmpty()) {
            String[] permissions = permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(LocateActivity.this, permissions, 1);
        } else {
            requestLocation();
        }
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(this);
        String bingPic = pref.getString("bing_pic", null);
        if (bingPic != null) {
            Glide.with(this).load(bingPic).into(iv_Bing);
        } else {
            loadImage();
        }
        Intent intentService = new Intent(LocateActivity.this, UpdateService.class);
        startService(intentService);
    }

    private void requestLocation() {
        initLocation();
        mLocationClient.start();
        BaiDuLocationUtils.create(this, new BaiDuLocationUtils.OnLoadListener() {
            @Override
            public void onLoadSucceed(final BDLocation bdLocation, double latitude, double longitude) {
                mLatitude=latitude;
                mLongitude=longitude;
                MyLocationData myLocationData=new MyLocationData.Builder()
                        .accuracy(bdLocation.getRadius())
                        .direction(0)
                        .latitude(bdLocation.getLatitude())
                        .longitude(bdLocation.getLongitude())
                        .build();
                baiduMap.setMyLocationData(myLocationData);
                LatLng ll=new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
                MapStatus.Builder builder=new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
                BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.locat);
                OverlayOptions overlayOptions = new MarkerOptions()
                        .position(ll)
                        .icon(bitmapDescriptor)
                        //MarkerAnimateType包含3中方式： none (无效果)、drop(从天上掉下)、grow(从地面生长)
                        .animateType(MarkerOptions.MarkerAnimateType.drop);
                final Marker markerItem = (Marker) baiduMap.addOverlay(overlayOptions);
                baiduMap.setOnMyLocationClickListener(new BaiduMap.OnMyLocationClickListener() {
                    @Override
                    public boolean onMyLocationClick() {
                        UseInfoFragment useInfoFragment = new UseInfoFragment();
                        Bundle bundle = new Bundle();
                        bundle.putDouble(LONGITUDE, bdLocation.getLongitude());
                        bundle.putDouble(LATITUDE, bdLocation.getLatitude());
                        useInfoFragment.setArguments(bundle);
                        useInfoFragment.show(getSupportFragmentManager(), "UserInfoFragmentDialog");
                        return true;
                    }
                });
                //标注点击事件
//                baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
//                    @Override
//                    public boolean onMarkerClick(Marker marker) {
//                        if (marker == markerItem) {
//                            Toast.makeText(LocateActivity.this, "点击数据", Toast.LENGTH_SHORT).show();
//                            UseInfoFragment useInfoFragment = new UseInfoFragment();
//                            Bundle bundle = new Bundle();
//                            bundle.putDouble(LONGITUDE, bdLocation.getLongitude());
//                            bundle.putDouble(LATITUDE, bdLocation.getLatitude());
//                            useInfoFragment.setArguments(bundle);
//                            useInfoFragment.show(getSupportFragmentManager(), "UserInfoFragmentDialog");
//                        }
//                        return true;
//                    }
//                });
            }
        });
    }

    private void initLocation() {
        //每隔5秒更新位置
        LocationClientOption option = new LocationClientOption();
        option.setScanSpan(5000);
        option.setOpenGps(true);
        //获取当前位置详细信息
        option.setIsNeedAddress(true);
        option.setLocationMode(LocationClientOption.LocationMode.Device_Sensors);
        mLocationClient.setLocOption(option);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    for (int result : grantResults) {
                        if (result != PackageManager.PERMISSION_GRANTED) {
                            Toast.makeText(this, "必须同意所有权限才能使用本程序", Toast.LENGTH_SHORT).show();
                            finish();
                            return;
                        }
                    }
                    requestLocation();
                } else {
                    Toast.makeText(this, "发生未知的错误", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
        }
    }

    public class MyLocationListener implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            getData(bdLocation.getLatitude(), bdLocation.getLongitude());
            StringBuilder currentPosition = new StringBuilder();
            currentPosition.append("纬度: ").append(bdLocation.getLatitude()).append("\n");
            currentPosition.append("经度: ").append(bdLocation.getLongitude()).append("\n");
            currentPosition.append("国家: ").append(bdLocation.getCountry()).append("\n");
            currentPosition.append("省: ").append(bdLocation.getProvince()).append("\n");
            currentPosition.append("市: ").append(bdLocation.getCity()).append("\n");
            currentPosition.append("区: ").append(bdLocation.getDistrict()).append("\n");
            currentPosition.append("街道: ").append(bdLocation.getStreet()).append("\n");
            currentPosition.append("定位方式: ");
            if (bdLocation.getLocType() == BDLocation.TypeGpsLocation) {
                currentPosition.append("GPS");
            } else if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation) {
                currentPosition.append("网络");
            }
//            tv_position.setText(currentPosition);
            if (bdLocation.getLocType() == BDLocation.TypeNetWorkLocation || bdLocation.getLocType() == BDLocation.TypeGpsLocation) {
//                navigateTo(bdLocation);
            }
        }
    }

    private void getData(double latitude, double longitude) {
        OkGo.<String>get(NewsApi.GEO)
                .tag(this)
                .params("lon", longitude)
                .params("lat", latitude)
                .params("format", 2)
                .params("dtype", "json")
                .params("key", "60f7fc28a4b0e9e8816813b2db7ed5f0")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String s = response.body();
                        Log.i(TAG, "onSuccess: " + s);
                    }
                });
    }

    //加载Bing图片
    private void loadImage() {
        String requestBingPic = "http://guolin.tech/api/bing_pic";
        HttpUtil.sendOkHttpRequest(requestBingPic, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, okhttp3.Response response) throws IOException {
                final String bingPic = response.body().string();
                SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(LocateActivity.this).edit();
                editor.putString("bing_Pic", bingPic);
                editor.apply();
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Glide.with(LocateActivity.this).load(bingPic).into(iv_Bing);
                    }
                });
            }
        });
    }

    private void navigateTo(final BDLocation location) {
        LatLng ll = new LatLng(location.getLatitude(), location.getLongitude());
        MapStatusUpdate update = MapStatusUpdateFactory.newLatLng(ll);
        //将地图移动到指定的经纬度
        baiduMap.animateMapStatus(update);
        //值越大，地图越精细
        update = MapStatusUpdateFactory.zoomBy(8f);
        baiduMap.animateMapStatus(update);
        BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.fromResource(R.mipmap.locat);
        OverlayOptions overlayOptions = new MarkerOptions()
                .position(ll)
                .icon(bitmapDescriptor)
                //MarkerAnimateType包含3中方式： none (无效果)、drop(从天上掉下)、grow(从地面生长)
                .animateType(MarkerOptions.MarkerAnimateType.drop);
        final Marker markerItem = (Marker) baiduMap.addOverlay(overlayOptions);
        //标注点击事件
        baiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(Marker marker) {
                if (marker == markerItem) {
                    Toast.makeText(LocateActivity.this, "点击数据", Toast.LENGTH_SHORT).show();
                    UseInfoFragment useInfoFragment = new UseInfoFragment();
                    Bundle bundle = new Bundle();
                    bundle.putDouble(LONGITUDE, location.getLongitude());
                    bundle.putDouble(LATITUDE, location.getLatitude());
                    useInfoFragment.setArguments(bundle);
                    useInfoFragment.show(getSupportFragmentManager(), "UserInfoFragmentDialog");
                }
                return true;
            }
        });
        //百度地图拖拽事件
        baiduMap.setOnMarkerDragListener(new BaiduMap.OnMarkerDragListener() {
            @Override
            public void onMarkerDrag(Marker marker) {

            }

            @Override
            public void onMarkerDragEnd(Marker marker) {

            }

            @Override
            public void onMarkerDragStart(Marker marker) {

            }
        });
        MyLocationData.Builder locationBuilder = new MyLocationData.Builder();
        locationBuilder.latitude(location.getLatitude());
        locationBuilder.longitude(location.getLongitude());
        MyLocationData locationData = locationBuilder.build();
        baiduMap.setMyLocationData(locationData);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stop();
        mapView.onDestroy();
        baiduMap.setMyLocationEnabled(false);
    }
}
